package com.imut.lagain.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imut.lagain.entity.HealthReminder;
import com.imut.lagain.mapper.HealthReminderMapper;
import com.imut.lagain.service.IHealthReminderService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * 健康提醒服务实现类
 */
@Service
public class HealthReminderServiceImpl extends ServiceImpl<HealthReminderMapper, HealthReminder> implements IHealthReminderService {
    private static final Logger log = LoggerFactory.getLogger(HealthReminderServiceImpl.class);

    
    /**
     * 根据用户ID和提醒时间范围查询健康提醒
     * @param userId 用户ID
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 健康提醒列表
     */
    public List<HealthReminder> findByUserIdAndTimeRange(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .between(HealthReminder::getRemindTime, startTime, endTime)
                .orderByAsc(HealthReminder::getRemindTime)
                .list();
    }
    
    /**
     * 根据用户ID和提醒类型查询健康提醒
     * @param userId 用户ID
     * @param reminderType 提醒类型
     * @param page 分页参数
     * @return 健康提醒分页列表
     */
    public IPage<HealthReminder> findByUserIdAndType(Long userId, String reminderType, Page<HealthReminder> page) {
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .eq(HealthReminder::getReminderType, reminderType)
                .orderByDesc(HealthReminder::getRemindTime)
                .page(page);
    }
    
    /**
     * 查询待处理的健康提醒
     * @param userId 用户ID
     * @param currentTime 当前时间
     * @return 健康提醒列表
     */
    public List<HealthReminder> findPendingReminders(Long userId, LocalDateTime currentTime) {
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .eq(HealthReminder::getIsCompleted, 0)
                .le(HealthReminder::getRemindTime, currentTime)
                .orderByAsc(HealthReminder::getRemindTime)
                .list();
    }
    
    /**
     * 标记提醒为已完成
     * @param id 提醒ID
     * @return 是否成功
     */
    public boolean markAsCompleted(Long id) {
        HealthReminder reminder = new HealthReminder();
        reminder.setIsCompleted(true);
        reminder.setCreateTime(LocalDateTime.now()); // 使用createTime字段代替updateTime
        return this.lambdaUpdate()
                .eq(HealthReminder::getId, id)
                .update(reminder);
    }
    
    /**
     * 根据用户ID查询健康提醒
     * @param userId 用户ID
     * @param page 分页参数
     * @return 健康提醒分页列表
     */
    public IPage<HealthReminder> findByUserId(Long userId, Page<HealthReminder> page) {
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .orderByDesc(HealthReminder::getCreateTime)
                .page(page);
    }
    
    /**
     * 根据提醒时间范围查询健康提醒
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param page 分页参数
     * @return 健康提醒分页列表
     */
    public IPage<HealthReminder> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime, Page<HealthReminder> page) {
        return this.lambdaQuery()
                .between(HealthReminder::getRemindTime, startTime, endTime)
                .orderByAsc(HealthReminder::getRemindTime)
                .page(page);
    }
    
    /**
     * 根据提醒类型查询健康提醒
     * @param reminderType 提醒类型
     * @param page 分页参数
     * @return 健康提醒分页列表
     */
    public IPage<HealthReminder> findByType(String reminderType, Page<HealthReminder> page) {
        return this.lambdaQuery()
                .eq(HealthReminder::getReminderType, reminderType)
                .orderByDesc(HealthReminder::getCreateTime)
                .page(page);
    }
    
    /**
     * 查询即将到期的健康提醒
     * @param userId 用户ID
     * @param currentTime 当前时间
     * @param timeRange 时间范围(分钟)
     * @return 健康提醒列表
     */
    public List<HealthReminder> findUpcomingReminders(Long userId, LocalDateTime currentTime, int timeRange) {
        LocalDateTime endTime = currentTime.plusMinutes(timeRange);
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .eq(HealthReminder::getIsCompleted, 0)
                .between(HealthReminder::getRemindTime, currentTime, endTime)
                .orderByAsc(HealthReminder::getRemindTime)
                .list();
    }
    
    /**
     * 统计用户健康提醒完成情况
     * @param userId 用户ID
     * @return 统计结果
     */
    public Map<String, Object> getReminderStatistics(Long userId) {
        Map<String, Object> statistics = new HashMap<>();
        long total = this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .count();
        long completed = this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .eq(HealthReminder::getIsCompleted, 1)
                .count();
        long pending = total - completed;
        statistics.put("total", total);
        statistics.put("completed", completed);
        statistics.put("pending", pending);
        return statistics;
    }
    
    /**
     * 根据用户ID查询未完成的提醒数量
     * @param userId 用户ID
     * @return 未完成的提醒数量
     */
    public Long countPendingReminders(Long userId) {
        return this.lambdaQuery()
                .eq(HealthReminder::getUserId, userId)
                .eq(HealthReminder::getIsCompleted, 0)
                .count();
    }
    
    @Override
    public Map<String, Object> getSymptomAnalysis(Long userId) {
        Map<String, Object> analysis = new HashMap<>();
        try {
            // 获取用户的健康提醒记录
            List<HealthReminder> reminders = this.lambdaQuery()
                    .eq(HealthReminder::getUserId, userId)
                    .orderByDesc(HealthReminder::getCreateTime)
                    .last("LIMIT 100") // 限制最近100条记录
                    .list();
            
            if (reminders.isEmpty()) {
                analysis.put("hasData", false);
                analysis.put("message", "暂无症状数据");
                return analysis;
            }
            
            // 分析症状频率
            Map<String, Integer> symptomFrequency = new HashMap<>();
            Map<String, Integer> typeFrequency = new HashMap<>();
            
            for (HealthReminder reminder : reminders) {
                String content = reminder.getMessage();
                String type = reminder.getReminderType();
                
                if (content != null) {
                    symptomFrequency.put(content, symptomFrequency.getOrDefault(content, 0) + 1);
                }
                if (type != null) {
                    typeFrequency.put(type, typeFrequency.getOrDefault(type, 0) + 1);
                }
            }
            
            analysis.put("hasData", true);
            analysis.put("totalRecords", reminders.size());
            analysis.put("symptomFrequency", symptomFrequency);
            analysis.put("typeFrequency", typeFrequency);
            analysis.put("analysisDate", LocalDateTime.now());
            
            // 找出最常见的症状
            String mostCommonSymptom = symptomFrequency.entrySet().stream()
                    .max(Map.Entry.comparingByValue())
                    .map(Map.Entry::getKey)
                    .orElse("无");
            analysis.put("mostCommonSymptom", mostCommonSymptom);
            
        } catch (Exception e) {
            log.error("获取症状分析失败", e);
            analysis.put("hasData", false);
            analysis.put("error", "获取症状分析失败: " + e.getMessage());
        }
         return analysis;
     }
     
     @Override
     public List<Map<String, Object>> getHealthTips(Long userId, String category) {
         List<Map<String, Object>> tips = new ArrayList<>();
         try {
             // 根据分类提供不同的健康小贴士
             switch (category != null ? category.toLowerCase() : "general") {
                 case "period":
                     tips.add(createHealthTip("🩸", "生理期护理", "保持充足休息，避免剧烈运动"));
                     tips.add(createHealthTip("🥛", "营养补充", "多喝温水，补充铁质和维生素"));
                     tips.add(createHealthTip("🛁", "个人卫生", "勤换卫生用品，保持私处清洁"));
                     break;
                 case "mood":
                     tips.add(createHealthTip("😊", "情绪管理", "保持积极心态，适当运动释放压力"));
                     tips.add(createHealthTip("🧘", "放松技巧", "尝试冥想或深呼吸练习"));
                     tips.add(createHealthTip("👥", "社交支持", "与朋友家人分享感受，寻求支持"));
                     break;
                 case "nutrition":
                     tips.add(createHealthTip("🥗", "均衡饮食", "多吃蔬菜水果，保持营养均衡"));
                     tips.add(createHealthTip("💧", "充足水分", "每天饮水8杯，保持身体水分"));
                     tips.add(createHealthTip("🚫", "避免刺激", "减少咖啡因和酒精摄入"));
                     break;
                 default:
                     tips.add(createHealthTip("💤", "充足睡眠", "保证每天7-8小时优质睡眠"));
                     tips.add(createHealthTip("🏃", "适量运动", "每周至少150分钟中等强度运动"));
                     tips.add(createHealthTip("🧘", "压力管理", "学会放松，管理生活压力"));
                     break;
             }
         } catch (Exception e) {
             log.error("获取健康小贴士失败", e);
             Map<String, Object> errorTip = new HashMap<>();
             errorTip.put("icon", "⚠️");
             errorTip.put("title", "错误");
             errorTip.put("content", "获取健康小贴士失败");
             tips.add(errorTip);
         }
         return tips;
     }
     
     private Map<String, Object> createHealthTip(String icon, String title, String content) {
         Map<String, Object> tip = new HashMap<>();
         tip.put("icon", icon);
         tip.put("title", title);
         tip.put("content", content);
         tip.put("timestamp", LocalDateTime.now());
         return tip;
     }
}
